package com.cn.dim.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cn.dim.pojo.Auth;
import com.cn.dim.pojo.Pages;
import com.cn.dim.pojo.Position;
import com.cn.dim.pojo.Role;
import com.cn.dim.service.RoleService;
import com.cn.dim.utils.MenuTreeBuilder;
import com.github.pagehelper.Page;


@Controller
@RequestMapping("/role")
public class RoleController {

	@Resource
	private RoleService roleService;
	@RequestMapping(value ="/queryRole",method = RequestMethod.GET)
	@ResponseBody
	//Pages是自己定义的页面实体类
	public Map<String,Object> queryRole(HttpServletRequest request,Role r,Pages pages){
		Map<String,Object> param=new HashMap<>();//定义查询参数
		Map<String,Object> reMap=new HashMap<>();//定义返回值，其中有一项必须是集合，先按照下面的写法做
		param.put("pageIndex",  pages.getPage());
		param.put("pageSize",pages.getRows());
		param.put("role", r);
		
		try {
			Page<Map<String,Object>> rList = (Page)roleService.queryRole(param);
			//Page对象认为是一个以键值对保存的一行记录的多条记录的集合，
			//可以在每行的键值对中补充一个键值对，用于页面显示“对应功能模块列”，
			for(Map m:rList){
				
				Map<String,Object> queryAuthPara=new HashMap<>();//定义queryAuth方法查询参数
				queryAuthPara.put("roleid", m.get("id"));
				List<Map<String,Object>> auths=roleService.queryAuth(queryAuthPara);//定义queryAuth方法返回结果集对象
				
				String authShowStr=getauthShowStr(auths);
				m.put("authShowStr", authShowStr);//在每行记录中补充1个用于显示的键值对
			}
			System.out.println(rList);
			reMap.put("rows", rList);
			reMap.put("total", rList.getTotal());
			reMap.put("status", "success");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	
	//将权限菜单的结果集转换为“某某,某某,某某”的形式（辅助方法）
	private String getauthShowStr(List<Map<String,Object>> auths )
	{
		String authShowStr="";
		//循环这个权限（菜单）结果集
		for(Map auth:auths)
		{
			authShowStr=authShowStr+auth.get("menushow")+" , ";
		}
		if(!authShowStr.equals(""))
		{
			authShowStr=authShowStr.substring(0, authShowStr.length()-2);//去掉最后一个逗号（由于逗号前有空格，因此-2）
		}
		return authShowStr;
	}
	
	@RequestMapping(value ="/insertRole",method = RequestMethod.POST)
	@ResponseBody
	//注意第二个参数是页面传过来的勾选的权限菜单的id集合，以键值对的方式保存，参数名要与页面中一致；；
	public Map<String,Object> insertRole(Role r,String aids)  
	{
		Map<String,Object> reMap=new HashMap<>();//返回值map
		String roleid=com.cn.dim.utils.StringUtil.makeUUID();
		r.setId(roleid);//主键
		r.setIsdel("0");//删除标记位
		
		JSONArray jsonArray=JSONArray.fromObject(aids);
        List<Map<String,Object>> r_as=(List<Map<String,Object>>)JSONArray.toList(jsonArray, Map.class);
        for(Map m:r_as)
        {
        	m.put("roleid", roleid);//构建插入中间表的数据
        }
		
		//这里补充创建人的id的代码
		
		try 
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date cdate = sdf.parse(sdf.format(new Date()));//创建日期
			r.setCreatetime(cdate);

			int flag = roleService.insertRole(r,r_as);
			if(flag>0)
			{
				reMap.put("message", "插入成功");
				reMap.put("status", "success");
			}
			else
			{
				reMap.put("status", "error");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	
	//固定写法，不用太追究
	@RequestMapping(value ="/queryAllAuth",method = RequestMethod.GET)
	public String queryAllAuth(HttpServletResponse response){
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		List<Auth> rList = new ArrayList<>();
		Map<String,Object> params = new  HashMap<>();
		try
		{
			rList =roleService.queryAllAuth(params);
			
			List<Auth> nodes = rList;
	        //拼装树形json字符串
			String json  = new MenuTreeBuilder().buildTree(nodes);

			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.getWriter().write(json);
			response.getWriter().flush();
		}
		catch (IOException e){
			e.getStackTrace();
		}
		return null;
	}

	@RequestMapping(value ="/updateRole",method = RequestMethod.POST)
	@ResponseBody
	//注意第二个参数是页面传过来的当前对象的id，第三个参数是勾选的权限菜单的id集合，以键值对的方式保存；
	public Map<String,Object> updateRole(Role r,String roleid,String aids)   
	{
		Map<String,Object> reMap=new HashMap<>();//返回值map
		r.setId(roleid);//实体对象传来的并不含有id的值，这里需要要使用页面传过来roleid值进行充
		JSONArray jsonArray=JSONArray.fromObject(aids);
        List<Map<String,Object>> r_as=(List<Map<String,Object>>)JSONArray.toList(jsonArray, Map.class);
        for(Map m:r_as)
        {
        	m.put("roleid", r.getId());//构建插入中间表的数据
        }
        
        Map<String,Object> m=new HashMap<>();//构建删除中间表的数据，service接口中updateRole方法的第二个参数
        m.put("roleid", r.getId());//这个map是用于删除中间表的参数map
		
		//这里补充修改（删除）人的id的代码
		
		try 
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date cdate = sdf.parse(sdf.format(new Date()));//修改（删除）日期
			r.setUpdatetime(cdate);
			
			int flag = roleService.updateRole(r,m,r_as);
			if(flag>0)
			{
				reMap.put("message", "修改成功");
				reMap.put("status", "success");
			}
			else
			{
				reMap.put("status", "error");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}

	@RequestMapping(value ="/delRole",method = RequestMethod.POST)//这个POST有待商榷
	@ResponseBody
	public Map<String,Object> delRole(HttpServletRequest request,String roleid)   //插入�?条单�?的role记录
	{
		Map<String,Object> reMap=new HashMap<>();//返回值map
        Map<String,Object> m=new HashMap<>();//删除中间表的参数，
        m.put("roleid", roleid);
		
		//这里补充修改（删除）人的id的代码
		
		try 
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date cdate = sdf.parse(sdf.format(new Date()));//修改（删除）日期
			m.put("updatetime", cdate);
			
			int flag = roleService.delRole(m);
			if(flag>0)
			{
				reMap.put("message", "删除成功");
				reMap.put("status", "success");
			}
			else
			{
				reMap.put("status", "error");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	
	@RequestMapping(value ="/queryRoleById",method = RequestMethod.GET)
	@ResponseBody
	public Map<String,Object> queryRoleById(HttpServletRequest request,String roleid){
		Map<String,Object> m=new HashMap<>();
		Map<String,Object> reMap=new HashMap<>();
		m.put("roleid", roleid);
		try {
			Role role =roleService.queryRoleById(m);
			reMap.put("data", role);
			reMap.put("status", "success");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	@RequestMapping(value ="/queryAuth",method = RequestMethod.GET)
	@ResponseBody
	public Map<String,Object> queryAuth(HttpServletRequest request,Role p){
		Map<String,Object> param=new HashMap<>();
		Map<String,Object> reMap=new HashMap<>();
		param.put("roleid", p.getId());
		try {
			List<Map<String,Object>> list =roleService.queryRoleAndAuth(param);
			reMap.put("data", list);
			reMap.put("status", "success");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
}
